<template>
  <v-container class="auth-container auth-text" fluid>
    <v-row justify="center">
      <v-col cols="12" sm="8" md="10" lg="8">
        <v-card class="elevation-6">
          <v-row no-gutters>
            <!-- 左侧图片 -->
            <v-col cols="12" md="6" class="d-none d-md-flex">
              <v-img
                src="../ico/logo.png"
                alt="Logo"
                height="100%"
                cover
                class="logo-img"
              ></v-img>
            </v-col>

            <!-- 右侧注册表单 -->
            <v-col cols="12" md="6" class="pa-6">
              <v-card-title class="text-h5 grey lighten-2">
                注册
              </v-card-title>
              <v-card-text>
                <v-form @submit.prevent="getVerificationCode">
                  <v-text-field
                    v-model="registerData.username"
                    label="用户名"
                    required
                    :disabled="loading"
                  ></v-text-field>
                  <v-text-field
                    v-model="registerData.email"
                    label="邮箱"
                    type="email"
                    required
                    :disabled="loading"
                  ></v-text-field>
                  <v-btn 
                    type="submit" 
                    color="primary" 
                    block 
                    class="mt-4"
                    :loading="codeLoading"
                    :disabled="codeLoading || loading"
                  >
                    {{ codeLoading ? '发送中...' : '获取验证码' }}
                  </v-btn>
                </v-form>

                <v-form v-if="showCaptcha" @submit.prevent="submitVerificationCode">
                  <v-text-field
                    v-model.number="captchaData.code"
                    label="验证码"
                    type="number"
                    required
                    :disabled="loading"
                  ></v-text-field>
                  <v-btn 
                    type="submit" 
                    color="success" 
                    block 
                    class="mt-4"
                    :loading="loading"
                    :disabled="loading"
                  >
                    {{ loading ? '验证中...' : '提交验证码' }}
                  </v-btn>
                </v-form>

                <!-- 返回登录链接 -->
                <div class="text-center mt-4">
                  <v-btn
                    variant="text"
                    color="primary"
                    @click="goToLogin"
                    :disabled="loading"
                  >
                    已有账号？返回登录
                  </v-btn>
                </div>

                <div class="text-center mt-4">
                  <v-btn color="secondary" @click="$router.push('/admin/login')" class="ml-2">
                    <v-icon start>mdi-account-key</v-icon>管理员登录
                  </v-btn>
                </div>
              </v-card-text>
            </v-col>
          </v-row>
        </v-card>
      </v-col>
    </v-row>

    <!-- 成功提示 -->
    <v-snackbar v-model="showSuccess" color="success">
      {{ successMessage }}
      <template v-slot:actions>
        <v-btn color="white" text @click="showSuccess = false">
          关闭
        </v-btn>
      </template>
    </v-snackbar>

    <!-- 错误提示 -->
    <v-snackbar v-model="showError" color="error">
      {{ errorMessage }}
      <template v-slot:actions>
        <v-btn color="white" text @click="showError = false">
          关闭
        </v-btn>
      </template>
    </v-snackbar>
  </v-container>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';

const { proxy } = getCurrentInstance();
const router = useRouter();

// 初始化注册数据
const registerData = ref({
  username: '',
  email: ''
});

// 初始化验证码数据
const captchaData = ref({
  code: null
});

// 是否显示验证码输入框
const showCaptcha = ref(false);

// 加载状态
const loading = ref(false);
const codeLoading = ref(false);

// 提示消息
const showSuccess = ref(false);
const showError = ref(false);
const successMessage = ref('');
const errorMessage = ref('');

// 获取验证码方法
const getVerificationCode = async () => {
  if (!registerData.value.username || !registerData.value.email) {
    showErrorMessage('请填写完整的注册信息');
    return;
  }

  try {
    codeLoading.value = true;
    // 发送注册信息以获取验证码
    const response = await proxy.$api.registerUser(registerData.value);
    console.log('验证码已发送:', response.data);
    showCaptcha.value = true; // 显示验证码输入框
    showSuccessMessage('验证码已发送，请查收！');
  } catch (error) {
    console.error('获取验证码失败:', error);
    showErrorMessage('获取验证码失败，请重试');
  } finally {
    codeLoading.value = false;
  }
};

// 提交验证码方法
const submitVerificationCode = async () => {
  if (!captchaData.value.code) {
    showErrorMessage('请输入验证码');
    return;
  }

  try {
    loading.value = true;
    // 提交验证码进行验证
    const captchaResponse = await proxy.$api.verifyRegisterCode(captchaData.value);
    console.log('注册成功:', captchaResponse.data);

    showSuccessMessage('注册成功！正在跳转到登录页面...');
    
    // 延迟跳转到登录页面
    setTimeout(() => {
      router.push('/login');
    }, 2000);
    
  } catch (error) {
    console.error('验证码验证失败:', error);
    showErrorMessage('验证码验证失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login');
};

// 显示成功消息
const showSuccessMessage = (message) => {
  successMessage.value = message;
  showSuccess.value = true;
};

// 显示错误消息
const showErrorMessage = (message) => {
  errorMessage.value = message;
  showError.value = true;
};
</script>

<style scoped>
.auth-container {
  max-width: 80%;
  margin-top: 3rem;
}
</style>